// pages/exam/exam.ts
import { ExamPaper, Question, QuestionOption } from '../../../utils/examTypes';
import { ExamUtils } from '../../../utils/examUtils';

Page({
  data: {
    paperId: 0, // 试卷ID
    recordId: 0, // 考试记录ID
    examPaper: {} as ExamPaper, // 试卷信息
    questions: [] as Question[], // 题目列表
    currentIndex: 0, // 当前题目索引
    progress: "" as string, // 进度百分比
    animationConfig: {
      duration: 300,
      timingFunction: 'ease-in-out'
    },
    selectedOptions: {}, // 记录每道题的选择 {题号: 选项}
    optionClassMapList: [] as { [key: string]: string }[], // 选项样式映射列表
    favoriteStatus: {} as { [key: number]: boolean } // 收藏状态
  },

  onLoad(options: any) {
    const recordId = parseInt(options.recordId);
    const paperId = parseInt(options.paperId);
    this.setData({ recordId, paperId });
    //debugger
    this.loadQuestionList(recordId, paperId);
  },

  // 加载题目列表
  async loadQuestionList(recordId: number, paperId: number) {
    this.setData({ loading: true });
    wx.showLoading({ title: '加载题目中...', mask: true });

    try {
      //debugger
      // const examRecord = await this.examStart(paperId);
      // console.log("examRecord:", examRecord);
      const examPaperResponse = await ExamUtils.fetchQuestionList(recordId, paperId);
      const questionList = examPaperResponse.questionAnswerList;
      const examPaper = examPaperResponse.examPaper;

      let currentIndex = 0;
      // 转换题目数据格式
      const formattedQuestions = questionList.map((q, index) => {
        // 检查当前问题的用户答案是否非空
        if (q.userAnswer && q.userAnswer.trim() !== '') {
          currentIndex = index; // 更新为当前下标（自动记录最后一个）
        }

        return {
          questionId: q.questionId,
          questionNo: q.questionNo,
          content: ExamUtils.stripHtmlTags(q.content),
          options: q.options.map(opt => ({
            questionNo: opt.questionNo,
            optionNo: opt.optionNo,
            content: ExamUtils.stripHtmlTags(opt.content),
          })),
          correctAnswer: q.correctAnswer, // 正确答案
          answerAnalysis: ExamUtils.stripHtmlTags(q.answerAnalysis),
          userAnswer: q.userAnswer, // 用户选择的选项
          showExplanation: q.userAnswer != null && q.userAnswer != q.correctAnswer, // 是否显示解析
          favorite: q.favorite || false // 是否已收藏
        };
      });
      console.log(formattedQuestions);

      // 初始化选项样式映射列表
      const optionClassMapList = formattedQuestions.map(question => {
        const map: { [key: string]: string } = {};
        question.options.forEach(option => {
          map[option.optionNo] = this.getOptionClass(question, option);
        });
        return map;
      });

      this.setData({
        examPaper: examPaper,
        questions: formattedQuestions,
        currentIndex: currentIndex,
        progress: ExamUtils.calculateProgress(currentIndex, formattedQuestions.length),
        optionClassMapList
      });

      // this.setData({ questionList });
    } catch (error) {
      console.error('加载题目失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'error',
        duration: 2000
      });
    } finally {
      this.setData({ loading: false });
      wx.hideLoading();
    }
  },

  // 滑动切换题目
  handleSwiperChange(e: any) {
    const current = e.detail.current;
    this.updateCurrentIndex(current);
  },
  prevQuestion() {
    const { currentIndex } = this.data;
    if (currentIndex > 0) {
      this.updateCurrentIndex(currentIndex - 1);
    }
  },
  nextQuestion() {
    const { currentIndex, questions } = this.data;
    if (currentIndex < questions.length - 1) {
      this.updateCurrentIndex(currentIndex + 1);
    }
  },
  async confirmSubmit() {
    try {
      // 1. 调用接口提交数据
      await ExamUtils.examFinish(
        this.data.paperId,
        this.data.recordId
      );

      // 2. 获取页面栈
      const pages = getCurrentPages();
      if (pages.length < 2) return; // 确保有上一页

      // 3. 获取上一页实例
      const prevPage = pages[pages.length - 2];

      // 4. 返回上一页
      wx.navigateBack({
        delta: 1,
        success: () => {
          // 5. 调用上一页的刷新方法，这里不需要传递参数，因为上一页的data中已经有paperId
          if (prevPage && typeof prevPage.loadExamRecords === 'function') {
            prevPage.loadExamRecords(); // 注意：这里不传参，因为上一页的loadExamRecords方法内部会使用this.data.paperId
            // 或者也可以传递prevPage.data.paperId作为参数，但两种方式都可以，只要上一页的方法支持
          }
        }
      });

    } catch (error) {
      console.error('提交失败:', error);
      wx.showToast({
        title: '提交失败',
        icon: 'none'
      });
    }

  },
  // 更新当前索引
  updateCurrentIndex(index: number) {
    this.setData({
      currentIndex: index,
      progress: ExamUtils.calculateProgress(index, this.data.questions.length)
    });
  },

  // 获取选项的样式类
  getOptionClass(question: any, option: any): string {
    if (question.userAnswer != null && question.correctAnswer === option.optionNo) {
      return 'corrected';
    } else if (question.userAnswer === option.optionNo) {
      return 'incorrected';
    }
    return '';
  },

  // 计算指定题目的选项样式类映射
  calculateOptionClassMap(questionIndex: number) {
    const { questions, optionClassMapList } = this.data;
    const question = questions[questionIndex];

    // 创建新的样式映射对象
    const newOptionClassMap: { [key: string]: string } = {};
    question.options.forEach(option => {
      newOptionClassMap[option.optionNo] = this.getOptionClass(question, option);
    });

    // 更新指定索引的样式映射
    const newOptionClassMapList = [...optionClassMapList];
    newOptionClassMapList[questionIndex] = newOptionClassMap;

    this.setData({
      optionClassMapList: newOptionClassMapList
    });
  },

  // 选择选项
  selectOption(e: any) {
    const { option, index } = e.detail;
    //debugger
    const { questions } = this.data;

    // 更新选择状态
    const updatedQuestions = [...questions];
    updatedQuestions[index] = {
      ...updatedQuestions[index],
      userAnswer: option,
      showExplanation: true
    };
    // 记录选择
    const selectedOptions = { ...this.data.selectedOptions };
    selectedOptions[questions[index].questionId] = option;

    this.setData({
      questions: updatedQuestions,
      selectedOptions
    });

    // 只更新当前题目的选项样式
    this.calculateOptionClassMap(index);

    // debugger
    const isCorrect = updatedQuestions[index].correctAnswer == option;

    ExamUtils.answer(this.data.recordId, this.data.paperId, updatedQuestions[index].questionId, updatedQuestions[index].userAnswer, isCorrect ? 1 : 0, 30);

    //如果答对了，自动下一题
    if (isCorrect) {
      const { currentIndex, questions } = this.data;
      if (currentIndex < questions.length - 1) {
        this.updateCurrentIndex(currentIndex + 1);
      }

    }

  },

  // 切换解析显示
  toggleExplanation(e: any) {
    const { index } = e.detail;
    const { questions } = this.data;
    const updatedQuestions = [...questions];
    updatedQuestions[index].showExplanation = !updatedQuestions[index].showExplanation;

    this.setData({
      questions: updatedQuestions
    });
  },

  getOptionStatus(question: any, option: any): string {
    return ExamUtils.getOptionStatus(question, option);
  },

  // 收藏题目
  async onFavorite(e: any) {
    const { currentIndex, questions } = this.data;

    try {
      const question = questions[currentIndex];
      const questionId = question.questionId;
      const favorite = !question.favorite;

      // 调用API更新收藏状态
      await ExamUtils.favoriteQuestion(questionId, this.data.recordId, this.data.paperId, favorite);

      // 更新本地状态
      const updatedQuestions = [...questions];
      updatedQuestions[currentIndex].favorite = favorite;

      this.setData({
        questions: updatedQuestions
      });

      wx.showToast({
        title: favorite ? '收藏成功' : '已取消收藏',
        icon: 'success'
      });
    } catch (error) {
      console.error('收藏操作失败:', error);
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      });
    }
  },

  // 对题目有异议
  async onReportIssue(e: any) {
    const { currentIndex, questions } = this.data;

    try {
      // 显示输入框让用户填写异议说明
      const remark = await new Promise((resolve) => {
        wx.showModal({
          title: '题目异议',
          editable: true,
          placeholderText: '请输入您对这道题目的异议...',
          success: (res) => {
            if (res.confirm) {
              resolve(res.content || '');
            } else {
              resolve(null);
            }
          }
        });
      });

      // 如果用户点击了取消，则不继续执行
      if (remark === null) return;

      const question = questions[currentIndex];
      const questionId = question.questionId;

      // 调用API提交异议
      await ExamUtils.reportQuestionIssue(questionId, this.data.recordId, this.data.paperId, remark as string);

      wx.showToast({
        title: '异议提交成功',
        icon: 'success'
      });
    } catch (error) {
      console.error('异议提交失败:', error);
      wx.showToast({
        title: '提交失败',
        icon: 'none'
      });
    }
  }
});